﻿setTimeout(() => {
	console.log('成功加载开关控制员 ( • ̀ω•́ )✧')

	_wts.createSubgrade('timer_$%^_tingwa')
	_wts.setTitle('听蛙时间控制员')

	const contentLayer = _wts.getContainer()
	let tipsLayer = null


	let isCounting = false
	let delayMinute = null
	let countDownSeconds = 0
	let timer = null

	const createDelayTimeInputBox = () => {
		const inputEl = document.createElement('input')
		const title = document.createElement('div')
		title.innerText = '请输入要延时关闭的时间 单位：分钟'
		inputEl.type = 'text'
		inputEl.placeholder = '在此输入'
		inputEl.style.margin = 3 + 'px'

		addInputBoxEvent(inputEl)
		contentLayer.appendChild(title)
		contentLayer.appendChild(inputEl)
	}

	const addInputBoxEvent = (inputBox) => {
		inputBox.onchange = () => {
			const val = inputBox.value
			if (checkIsNumStr(val)) {
				delayMinute = val * 1
			} else {
				console.log('请输入合法数字')
			}
		}
	}

	const createTipsLayer = () => {
		tipsLayer = document.createElement('div')
		tipsLayer.innerText = ''

		contentLayer.appendChild(tipsLayer)
	}

	const createTimingStopButton = () => {
		const btn = document.createElement('button')
		const title = `定时关闭`
		btn.innerText = title
		btn.style.margin = 3 + 'px'
		btn.style.fontSize = 10 + 'px'

		contentLayer.appendChild(btn)
		btn.onclick = () => delayPauseMusic(delayMinute)
	}

	const checkIsNumStr = (value) => !isNaN(value * 1)

	const delayPauseMusic = (delayMinute) => {
		const pauseBtn = document.querySelector('.pause')
		if (isCounting) {
			clearInterval(timer)
			console.log('清除原本的计时器，重新计时')
		}
		countDownSeconds = delayMinute * 60
		isCounting = true
		timer = setInterval(() => {
			countDownSeconds--
			refreshTips()
			if (countDownSeconds <= 0) {
				isCounting = false
				pauseBtn.click()
				clearInterval(timer)
			}
		}, 1 * 1000)
		console.log('运行中', delayMinute, '分钟后关闭')
	}

	const refreshTips = () => {
		tipsLayer.innerText = `
		${delayMinute ? countDownSeconds + ' 秒后关闭' : '时间还没设置好诶'}
		${isCounting ? '正在倒计时 ♪(･ω･)ﾉ' : '计时员休息中 ε=(´ο｀*)))'}
		`
	}

	// 主函数
	const main = () => {
		createDelayTimeInputBox()
		createTimingStopButton()
		createTipsLayer()
		refreshTips()

		if (location.href != 'https://www.itingwa.com/?c=player#reload') {
			contentLayer.parentNode.style.display = 'none'
		}
	}


	main()

}, 1 * 1000)

